package common

import (
	"github.com/golang/protobuf/proto"
	"leaf/core/cluster"
	"leaf/core/log"
	msg2 "leaf/core/msg"
	"leaf/pb"
	"reflect"
)

func SendMsg(sid int32, gid uint64, message proto.Message) {
	logicNode := cluster.GetNode(sid)
	if logicNode == nil {
		log.Error("SendNotify sid:%v gid:%v err:logicNode not find", sid, gid)
		return
	}
	if message == nil {
		log.Error("SendNotify sid:%v gid:%v err:message is nil", sid, gid)
		return
	}
	msgId := msg2.GetMessageId(reflect.TypeOf(message))
	if msgId == 0 {
		log.Error("SendNotify sid:%v gid:%v err:message not register", sid, gid)
		return
	}
	msgBytes, err := proto.Marshal(message)
	if err != nil {
		log.Error("SendNotify sid:%v gid:%v err:%v", sid, gid, err)
		return
	}
	logicNode.Cast("SendNotifyMsg", &pb.C2S_NotifyMsg{
		Gid:   proto.Uint64(gid),
		MsgId: proto.Int32(int32(msgId)),
		Msg:   msgBytes,
	})
}
